package com.qiuzhi.thread;

class MyThread extends Thread {
    volatile boolean stop = false;

    public void run() {
        while (!stop) {
            System.out.println(getName() + " 线程正在运行");
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                System.out.println("发生异常");
                stop = true; // 在异常处理代码中修改共享变量的状态
            }
        }
        System.out.println(getName() + " 线程退出");
    }
}

class InterruptThreadDemo3 {
    public static void main(String[] args) throws InterruptedException {
        MyThread m1 = new MyThread();
        System.out.println("开始启动线程");
        m1.start();
        Thread.sleep(3000);
        System.out.println("中断线程...: " + m1.getName());
        m1.stop = true; // 设置共享变量为true
        m1.interrupt(); // 阻塞时退出阻塞状态
        Thread.sleep(3000); // 主线程休眠3秒以便观察线程m1的中断情况
        System.out.println("正在停止应用程序...");
    }
}